/*
 * 据资料显示在js中单引号和双引号都是一样的，但是在使用是去碰到了问题，于是乎百度给我答案，
 * 说是平时使用的时候尽量用单引号，只有碰到嵌套的时候才会同时用两种引号。
 * 即外面是单引号的时候里面就要用双引号，外面是双引号的时候里面就要用单引号，总之不能同时用双引号或者是单引号
 * */

$(document).ready(function () {
    var totalPage;
    var currentPage;
    var items;
    var totalCount;

    /*上一页*/
    $('#previousPage').click(function () {
        $.ajax(
            {
                url: 'pagedQuery.do',
                type: 'POST',
                cache: false,
                async: false,//默认异步执行会出问题
                data: {"currentPage": currentPage - 1},
                dataType: "json",
                error: function () {
                    alert("error")
                },
                success: function (result) {//参数有result,status,xhr
                    applyTable(result);
                    applyPaged(result);
                }
            }
        )
    });
    /*下一页*/
    $('#nextPage').click(function () {
        //alert('点了下一页')
        $.ajax(
            {
                url: 'pagedQuery.do',
                type: 'POST',
                cache: false,
                async: false,//默认异步执行会出问题
                data: {"currentPage": currentPage + 1},
                dataType: "json",
                error: function () {
                    alert("error")
                },
                success: function (result) {//参数有result,status,xhr
                    applyTable(result);
                    applyPaged(result);
                }
            }
        )
    });

    /*页数列表1,2,3,4,5,6*/
    $('#no1,#no2,#no3,#no4,#no5,#no6').click(function () {
        var pageNo = $(this).val();
        if (pageNo == currentPage) {
            return;
        }
        $.ajax(
            {
                url: "pagedQuery.do",
                data: {"currentPage": pageNo},
                type: "POST",
                cache: false,
                async: false,
                dataType: "json",//虽然后台已经转换为了json格式并返回，但这里依然要声明数据类型为json，否则娶不到result中的属性值
                error: function () {
                    alert("error")
                },
                success: function (result) {//参数有result,status,xhr
                    //alert('点击了页数列表');
                    applyTable(result);
                    applyPaged(result);
                }
            });
    });

    $('#jumpTo').click(function () {
        var pageNo = $("#fillPageNo").val();
        if (pageNo == currentPage){
         alert('已在此页！');
         return;
         }
        jumpTo(pageNo);
    });

    function jumpTo(pageNo) {
        if (pageNo <= totalPage && pageNo >= 1) {
            $.ajax(
                {
                    url: 'pagedQuery.do',
                    type: 'POST',
                    cache: false,
                    async: false,//默认异步执行会出问题
                    data: {"currentPage": pageNo},
                    dataType: "json",
                    error: function () {
                        alert("error")
                    },
                    success: function (result) {//参数有result,status,xhr
                        applyTable(result);
                        applyPaged(result);
                    }
                }
            )
        } else {
            alert("无法到达该页");
        }
    }

    /*
     * 上传后返回数据时会自动加载原网页，会触发下面的刷新网页的ajax，所以这里不需要回调函数这个键值对
     * */
    $('#input2').click(function () {
        $.ajax({
            url: 'insertDataForBatch.do',
            type: 'POST',
            cache: false,
            async: false,//默认异步执行会出问题
            //不能有files[0]，否则无法访问insertDataForBatch.do，而只是刷新原网页
            data: new FormData($('#uploadForm')[0]),
            dataType: "json",
            // 告诉jQuery不要去处理发送的数据
            processData: false,
            // 告诉jQuery不要去设置Content-Type请求头
            contentType: false//这个参数在上传文件时用到，别的地方使用要谨慎
            /*
             * 这个ajax有点特殊，这里如果定义了回调函数处理返回结果，还会再调用刷新网页的ajax，
             * 而那些分页的ajax就不这样
             * */
        });
    });

    /*用于显示待上传的文件名*/
    $(".myFileUpload").change(function () {
        var arrs = $(this).val().split('\\');
        var filename = arrs[arrs.length - 1];
        $(".show").html(filename);
    });

    /*刷新网页时加载*/
    $.ajax({
        url: "pagedQuery.do",
        dataType: "json",//不能少
        type: "GET",
        global: "false",
        error: function () {
            alert('暂无数据！');
            applyPaged("");
        },
        success: function (result) {//参数有result,status,xhr
            //alert('手动刷新了网页');
            applyTable(result);
            applyPaged(result);
        }
    });

    function applyTable(result) {

        totalCount = result.totalCount;
        items = result.items;
        //为下面插入的标签加一个clss属性，然后作为选择器remove掉，试过大量的方法都无效，这样做几乎是最佳实践
        $(".trId").remove();
        /*
        每次渲染新一页的表格时先移除之前计算结果的行及其标题
         */
        removeCalculateRow();
        var intPageNo = parseInt(result.currentPage);
        $.each(items, function (index, e) {
            var tb = "<tr class=trId>" +
                "<td>" + ((intPageNo - 1) * 25 + index + 1) + "</td>" +
                "<td>" + e.a1 + "</td><td>" + e.a2 + "</td>" +
                "<td>" + e.a3 + "</td><td>" + e.a4 + "</td>" +
                "<td>" + e.a5 + "</td><td>" + e.a6 + "</td>" +
                "<td>" + e.a7 + "</td><td>" + e.a8 + "</td>" +
                "<td>" + e.a9 + "</td><td>" + e.a10 + "</td>" +
                "<td>" + e.a11 + "</td><td>" + e.a12 + "</td>" +
                "<td>" + e.quality + "</td>" +
                "</tr>";
            $("table").append(tb);
        });
        //$('body').append(content);
    }

    function applyPaged(result) {
        $("#no" + currentPage).css({'background': '#ddd', 'color': 'black'});
        //alert('"#no"+currentPage')//虽然上面的选择器打印不出来，但是却能起作用，很神奇
        currentPage = result.currentPage;
        totalPage = result.totalPage;

        document.cookie="currentPage="+currentPage;
/*        var name=document.cookie.split(";")[2].split("=")[0];
        var value=document.cookie.split(";")[2].split("=")[1];
        alert(name); alert(value);    */

        if (currentPage == totalPage) {
            $('#nextPage').attr('disabled', 'true')
        } else
            $('#nextPage').removeAttr('disabled');
        if (currentPage == 1) {
            $('#previousPage').attr('disabled', 'true');
        } else {
            $('#previousPage').removeAttr('disabled');
        }
        $("#no" + currentPage).css({'background': '#68A593', 'color': '#fff'});
        $('#showCurrentPage').empty();
        $('#showCurrentPage').append(currentPage);
        $('#showTotalPage').empty();
        $('#showTotalPage').append(totalPage);
        $('#fillPageNo').val('');//清空输入框
        if (result.length == 0) {
            $('#showCurrentPage').append('0');
            $('#showTotalPage').append('0');
        }
    }

    $('#calculateButton').click(function () {
        jumpTo(totalPage);
        $.ajax({
            url: 'calculate.do',
            type: 'POST',
            cache: false,
            async: false,
            dataType: "json",
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.readyState);
                alert(textStatus);
            },
            success: function (result) {//参数有result,status,xhr
                //alert("click-#calculate-ajax被调用");
                $("#title").remove();
                $("table").append('<tr id="title"><td colspan="15" height="45px"><h3 style="margin: 0px;">计算结果</h3></td></tr>');
                applyAverage(result[0]);
                applyStdDevP(result[1]);
                applyOutlierNumber(result[2]);
                applyFactorNumber(result[3]);
            }
        });
    });

    function applyAverage(average) {
        $("#average").remove();
        var averageRow = "<tr id='average'><td>avg</td>" +
            "<td>" + formatData(average.avgA1) + "</td><td>" + formatData(average.avgA2) + "</td>" +
            "<td>" + formatData(average.avgA3) + "</td><td>" + formatData(average.avgA4) + "</td>" +
            "<td>" + formatData(average.avgA5) + "</td><td>" + formatData(average.avgA6) + "</td>" +
            "<td>" + formatData(average.avgA7) + "</td><td>" + formatData(average.avgA8) + "</td>" +
            "<td>" + formatData(average.avgA9) + "</td><td>" + formatData(average.avgA10) + "</td>" +
            "<td>" + formatData(average.avgA11) + "</td><td>" + formatData(average.avgA12) + "</td>" +
            "<td>" + '-' + "</td>" +
            "</tr>";
        $("table").append(averageRow);
    }

    function applyStdDevP(stdDevP) {
        //alert('开始渲染标准差');
        $("#stdDevP").remove();
        var stdDevPRow = "<tr id='stdDevP'><td>std</td>" +
            "<td>" + stdDevP.stdDevPA1.toString().substr(0, 11) + "</td>" +
            "<td>" + stdDevP.stdDevPA2.toString().substr(0, 11) + "</td>" +
            "<td>" + stdDevP.stdDevPA3.toString().substr(0, 11) + "</td>" +
            "<td>" + stdDevP.stdDevPA4.toString().substr(0, 11) + "</td>" +
            "<td>" + stdDevP.stdDevPA5.toString().substr(0, 11) + "</td>" +
            "<td>" + stdDevP.stdDevPA6.toString().substr(0, 11) + "</td>" +
            "<td>" + stdDevP.stdDevPA7.toString().substr(0, 11) + "</td>" +
            "<td>" + stdDevP.stdDevPA8.toString().substr(0, 11) + "</td>" +
            "<td>" + stdDevP.stdDevPA9.toString().substr(0, 11) + "</td>" +
            "<td>" + stdDevP.stdDevPA10.toString().substr(0, 11) + "</td>" +
            "<td>" + stdDevP.stdDevPA11.toString().substr(0, 11) + "</td>" +
            "<td>" + stdDevP.stdDevPA12.toString().substr(0, 11) + "</td>" +
            "<td>" + '-' + "</td>" +
            "</tr>";
        $("table").append(stdDevPRow);

    }

    function applyOutlierNumber(outlierNumber) {
        $("#outlierNumber").remove();
        var outlierNumber = "<tr id='outlierNumber'><td>ns</td>" +
            "<td>" + outlierNumber.a1OutlierNumber + "</td>" +
            "<td>" + outlierNumber.a2OutlierNumber + "</td>" +
            "<td>" + outlierNumber.a3OutlierNumber + "</td>" +
            "<td>" + outlierNumber.a4OutlierNumber + "</td>" +
            "<td>" + outlierNumber.a5OutlierNumber + "</td>" +
            "<td>" + outlierNumber.a6OutlierNumber + "</td>" +
            "<td>" + outlierNumber.a7OutlierNumber + "</td>" +
            "<td>" + outlierNumber.a8OutlierNumber + "</td>" +
            "<td>" + outlierNumber.a9OutlierNumber + "</td>" +
            "<td>" + outlierNumber.a10OutlierNumber + "</td>" +
            "<td>" + outlierNumber.a11OutlierNumber + "</td>" +
            "<td>" + outlierNumber.a12OutlierNumber + "</td>" +
            "<td>" + '-' + "</td>" +
            "</tr>";
        $("table").append(outlierNumber);
    }

    function applyFactorNumber(factorNumber) {
        $("#factorNumber").remove();
        var factorNumber = "<tr id='factorNumber'><td>factor</td>" +
            "<td>" + '-' + "</td>" +
            "<td>" + '-' + "</td>" +
            "<td>" + '-' + "</td>" +
            "<td>" + '-' + "</td>" +
            "<td>" + '-' + "</td>" +
            "<td>" + '-' + "</td>" +
            "<td>" + '-' + "</td>" +
            "<td>" + '-' + "</td>" +
            "<td>" + '-' + "</td>" +
            "<td>" + '-' + "</td>" +
            "<td>" + '-' + "</td>" +
            "<td>" + '-' + "</td>" +
            "<td>" + factorNumber.qualityFactorNumber + "</td>" +
            "</tr>";
        $("table").append(factorNumber);
    }

    function removeCalculateRow() {
        $("#title").remove();
        $("#average").remove();
        $("#stdDevP").remove();
        $("#outlierNumber").remove();
        $("#factorNumber").remove();
    }

    function formatData(data) {
        /*测试证明，substr方法对于指定的位数超出实际位数就按照原长度返回*/
        /*        var str='12345';
         str=str.substr(0,6);
         alert('测试：'+str);*/
        if (data < 0) {
            data = data.toString().substr(0, 12);//注意substr方法第二个参数时length，不是index。
        } else {
            data = data.toString().substr(0, 11);
        }
        return data;
    }

});



